package com.ml.ws.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.ml.enums.RequestType;
import com.ml.ws.model.RequestParam;
import com.ml.ws.model.ResponseMessage;
import com.ml.ws.model.TradeDto;
import com.ml.ws.service.RequestFactory;
import com.ml.ws.service.RequestService;
import com.virgil.core.utils.GZipUtils;
import com.virgil.redis.util.RedisUtil;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;

@Service
public class ReqTrade implements RequestService, InitializingBean {

	@Autowired
	RedisUtil redisUtil;
	
	@Override
	public void pushReqData(Channel channel, RequestParam param) {
		try {
			List<String> trades = redisUtil.lrange(param.getSymbol() + ":pushRecordMarketDesc", 0,
					param.getSize() - 1,0);
			List<TradeDto> tradeDtos = new ArrayList<TradeDto>();
			for (String s : trades) {
				tradeDtos.add(JSON.parseObject(s, TradeDto.class));
			}
			// 封装消息体
			ResponseMessage message = new ResponseMessage("history_trades", tradeDtos);
			// 获取压缩后的数据
			byte[] bytes = GZipUtils.compress(JSON.toJSONString(message));
			// 转换成二进制数据
			ByteBuf buf = Unpooled.wrappedBuffer(bytes);
			channel.writeAndFlush(new BinaryWebSocketFrame(buf));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		RequestFactory.register(RequestType.TRADE, this);
	}
}
